import React, { useState } from "react";
import { Checkbox, Modal, Stepper, SwipeAction, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { AddOrUpdateCartParams, Cart } from "@/type/CartType";
import { useEnhanceDispatch } from "@/hooks";
import { changeChecked, deleteCartThunk, deleteGood, fetchCartListThunk, updateCartThunk } from "@/store/modules/cartStore";
import type { Action } from "antd-mobile/es/components/swipe-action";
import "./CartItem.scss";

interface CartItemProps {
   good: Cart;
}

const CartItem: React.FunctionComponent<CartItemProps> = ({ good }) => {
   const navigate = useNavigate();

   const enhanceDispatch = useEnhanceDispatch();

   // 更新购物车商品数量的参数
   const [params, setParams] = useState<AddOrUpdateCartParams>({
      goodsId: good.goods_id,
      goodsNum: good.goods_num,
      goodsSkuId: "0",
   });

   const rightActions: Action[] = [
      {
         key: "show",
         text: "详情",
         color: "warning",
      },
      {
         key: "delete",
         text: "删除",
         color: "danger",
      },
   ];

   /**
    * @description勾选商品
    * */
   const handleChecked = (checked: boolean) => {
      enhanceDispatch(changeChecked({ goods_id: good.goods_id, checked }));
   };

   /**
    * @description 删除商品
    * */
   const onAction = async (action: Action, event: React.MouseEvent) => {
      if (action.key == "delete") {
         const result: boolean = await Modal.confirm({ content: "确认此商品吗?" });
         if (!result) return;
         // enhanceDispatch(deleteGood(good.goods_id));
         await enhanceDispatch(deleteCartThunk([good.id])).unwrap();
         Toast.show("删除成功");
      } else if (action.key == "show") {
         navigate(`/good-detail?goodsId=${good?.goods_id}`);
      }
   };

   /**
    * @description 步进器的change回调函数
    * */
   const changeGoodsName = async (goodsName: number) => {
      const newParams = { ...params, goodsNum: goodsName };
      setParams(newParams);
      await enhanceDispatch(updateCartThunk(newParams)).unwrap();
      await enhanceDispatch(fetchCartListThunk()).unwrap();
   };

   return (
      <SwipeAction rightActions={rightActions} onAction={onAction}>
         <div className="cart-item">
            <div className="checkbox">
               <Checkbox checked={good.checked} onChange={handleChecked}></Checkbox>
            </div>
            <div className="image">
               <img src={good.goods.goods_image} alt="" />
            </div>
            <div className="info">
               <div className="top ellipsis-multi">{good.goods.goods_name}</div>
               <div className="bottom">
                  <span className="price">￥{good.goods.goods_price_max}</span>
                  <Stepper value={good.goods_num} onChange={changeGoodsName}></Stepper>
               </div>
            </div>
         </div>
      </SwipeAction>
   );
};

export default CartItem;
